/*
Problem:    Combination Sum
Notes:
Given a set of candidate numbers (C) and a target number (T), find all unique
combinations in C where the candidate numbers sums to T.

The same repeated number may be chosen from C unlimited number of times.

Note:
All numbers (including target) will be positive integers.
Elements in a combination (a1, a2, … ,ak) must be in non-descending order.
(ie, a1 ≤ a2 ≤ … ≤ ak).
The solution set must not contain duplicate combinations.
For example, given candidate set 2,3,6,7 and target 7,
A solution set is:
[7]
[2, 2, 3]

complete knapsack
f[i][v] = min(f[i][v - k * c[i]]) 0 <= k <= v / c[i]

f[i][v] = min(f[i-1][v], f[i][ v - c[i]])
*/
#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

class Solution {
public:
	vector<vector<int> > combinationSum(vector<int> &candidates, int target) {
		int len = candidates.size();
		bool* solved = new bool[target + 1];
		int** path = new int*[len + 1];
		for (int i = 0; i <= len; i++) {
			path[i] = new int[target + 1];
			path[i][0] = -1;
		}

		for (int i = 0; i <= target; i++) {
			solved[i] = false;
			path[0][i] = -1;
		}
		solved[0] = true;

		for (int i = 1; i <= len; i++) {
			for (int v = candidates[i - 1]; v <= target; v++) {
				if (solved[v] || solved[v - candidates[i - 1]]) {
					solved[v] = true;
					if (solved[v] && solved[v - candidates[i - 1]]) path[i][v] = 3;
					else if (solved[v - candidates[i - 1]]) path[i][v] = 2;
					else path[i][v] = 1;
				} else {
					solved[v] = false;
					path[i][v] = -1;
				}
			}
		}
		vector<vector<int> > result;
		vector<int> items;
		GetAllSolution(candidates, path, len, target, &items, &result);

		delete[] solved;
		for (int i = 0; i <= len; i++)
			delete[] path[i];
		delete[] path;

		return result;
	}

	void GetAllSolution(const vector<int> &candidates, int** path, int x, int y, vector<int>* items,
		vector<vector<int> >* result) {

		if (y == 0) {
			sort(items->begin(), items->end());
			result->push_back(*items);
			return;
		}
		if (path[x][y] == 1) {
			GetAllSolution(candidates, path, x - 1, y, items, result);
		}
		if (path[x][y] == 2) {
			items->push_back(candidates[x - 1]);
			GetAllSolution(candidates, path, x, y - candidates[x - 1], items, result);
			items->pop_back();
		}
		if (path[x][y] == 3) {
			GetAllSolution(candidates, path, x - 1, y, items, result);

			items->push_back(candidates[x - 1]);
			GetAllSolution(candidates, path, x, y - candidates[x - 1], items, result);
			items->pop_back();
		}
	}

};

int main(int argc, char* argv[])
{
	int a[] = {2, 3, 6, 7};
	vector<int> input;
	for (int i = 0; i < 4; i++)
		input.push_back(a[i]);

	Solution s;	
	vector<vector<int> > result = s.combinationSum(input, 7);
	for (int i = 0; i < result.size(); i++) {
		for (int j = 0; j < result[i].size(); j++)
			cout << result[i][j] << " ";
		cout << endl;
	}
	
	return 0;
}